//
//  GHLoginViewController.m
//  GodHorses
//
//  Created by Mac on 2017/11/14.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "TMRegisterViewController.h"
#import "UITextField+STInputLimit.h"
#import "TMForgotViewController.h"
#import "TMRegisterViewController.h"
#import "TMTabbarViewController.h"
#import "STSendButton.h"
#import "TMLoginViewController.h"
@interface TMRegisterViewController ()<STSendButtonDlegate>
@property(nonatomic, strong) UITextField                     *accountTextFiled;
@property(nonatomic, strong) UITextField                     *phoneTextFiled;
@property(nonatomic, strong) UITextField                     *pwdTextFiled;
@property(nonatomic, strong) UITextField                     *confimTextFiled;
@property(nonatomic, strong) UITextField                     *codeTextFiled;
@property(nonatomic, strong) STSendButton                     *sendButton;
@property(nonatomic, strong) UIScrollView                     *scrollView;/**< <##> */
@end

@implementation TMRegisterViewController
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
#pragma mark --vc 生命周期
- (void)viewDidLoad{
    [super viewDidLoad];
    [self configSubView];
    [self addNotifacations];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self st_hideNavagetionbarAnimated:NO];
    
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self st_showNavagationbarAnimated:NO];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
#pragma mark --Notifacation
- (void)addNotifacations{
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textFieldTextDidChangeNotification:)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:nil];
    
}
- (void)textFieldTextDidChangeNotification:(NSNotification*)notify{
    if (notify.object == self.pwdTextFiled) {
        [self.pwdTextFiled st_textInputLimitWithLength:16];
    }else if (notify.object == self.accountTextFiled){
        [self.accountTextFiled st_textInputLimitWithLength:11];
    }
}
- (void)dealloc{
    [self.sendButton timerEnd];
    self.sendButton = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)loadView{
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight)];
    self.scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.scrollView.backgroundColor = UIColor.whiteColor;
    self.automaticallyAdjustsScrollViewInsets = NO;
    if (ios11 && [self.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        [self.scrollView setContentInsetAdjustmentBehavior:@(2)];
    }
    self.view = self.scrollView;
}
#pragma mark --subView
- (void)configSubView{
    self.view.backgroundColor = UIColor.whiteColor;
    [self st_autoAdjustAllResponder];
    

    

    self.accountTextFiled = [UITextField new];
    self.phoneTextFiled = [UITextField new];
    self.pwdTextFiled = [UITextField new];
    self.pwdTextFiled.secureTextEntry = YES;
    self.confimTextFiled = [UITextField new];
    self.confimTextFiled.secureTextEntry = YES;
    self.codeTextFiled = [UITextField new];
    
    UIImageView * backImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 172)];
    backImageView.image = [UIImage imageNamed:@"羽毛"];
    [self.view addSubview:backImageView];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn addTarget:self action:@selector(back)  forControlEvents:UIControlEventTouchUpInside];
    [btn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateHighlighted];
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    btn.frame = CGRectMake(15, 20, 44, 44);
    [self.view addSubview:btn];
    
    UIImageView * iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 95, 46)];
    iconImageView.image = [UIImage imageNamed:@"轻聊"];
    iconImageView.st_centerX = UIScreenWidth /2;
    iconImageView.st_top = 80;
    [self.view addSubview:iconImageView];
    
    
    
    UIView * accountView = [TMUtils normalTextField:self.accountTextFiled title:@"用户名"];
    accountView.st_top = backImageView.bottom  +10;
    [self.view addSubview:accountView];
    
    UIView * phoneView = [TMUtils normalTextField:self.phoneTextFiled title:@"手机号码"];
    phoneView.st_top = accountView.bottom  +20;
    [self.view addSubview:phoneView];
    
    
    UIView * pwdView = [TMUtils normalTextField:self.pwdTextFiled title:@"密码"];
    pwdView.st_top = phoneView.st_bottom + 20;
    [self.view addSubview:pwdView];
    
    UIView * confimView = [TMUtils normalTextField:self.confimTextFiled title:@"确认密码"];
    confimView.st_top = pwdView.bottom  +20;
    [self.view addSubview:confimView];
    
    UIView * codeView = [TMUtils normalTextField:self.codeTextFiled title:@"手机验证码"];
    codeView.st_top = confimView.bottom  +20;
    self.codeTextFiled.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:codeView];
    
    self.sendButton = [[STSendButton alloc] initWithFrame:CGRectMake(0, 0, 100, 35) andWithDuration:60];
    self.sendButton.backgroundColor = [UIColor colorWithRed:177/255.0 green:177/255.0 blue:177/255.0 alpha:1];
    self.sendButton.delegate = self;
    self.sendButton.titleLabel.font = [UIFont systemFontOfSize:12];
    self.codeTextFiled.rightView = self.sendButton;
    [self.sendButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    self.codeTextFiled.rightViewMode = UITextFieldViewModeAlways;
    
    __weak typeof(self) weakSelf =  self;
    STButton * registerButton = [[STButton alloc] initWithFrame:CGRectMake(30, codeView.st_bottom + 40, UIScreenWidth - 60, 44)
                                                       title:@"注册"
                                                  titleColor:[UIColor whiteColor]
                                                   titleFont:18
                                                cornerRadius:22
                                             backgroundColor:TM_ThemeBackGroundColor
                                             backgroundImage:nil
                                                       image:nil];
    registerButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [registerButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedLoginButton];
    }];
    [self.view addSubview:registerButton];
    
    
    STButton * loginButton = [[STButton alloc] initWithFrame:CGRectMake(30, registerButton.bottom  +40, UIScreenWidth, 44)
                                                          title:@"还没有账号,去登录"
                                                     titleColor:SecendTextColor
                                                      titleFont:13
                                                   cornerRadius:0
                                                backgroundColor:[UIColor clearColor]
                                                backgroundImage:nil
                                                          image:nil];
    loginButton.centerX = UIScreenWidth/2;
    loginButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [loginButton setAttributedTitle:[loginButton.currentTitle st_convertAttributeStringWithKeyWord:@"登录" attributes:@{NSForegroundColorAttributeName:TM_ThemeBackGroundColor}] forState:UIControlStateNormal];
    [loginButton setClicAction:^(UIButton *sender) {
        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
    }];
    [self.view addSubview:loginButton];
    
    self.scrollView.contentSize = CGSizeMake(0, loginButton.bottom  +30);
    
}
#pragma mark --STSendButtonDlegate
- (BOOL)STSendButtonWillClic:(UIButton *)button{
    if (self.phoneTextFiled.text.length != 11) {
        [SVProgressHUD showErrorWithStatus:@"手机号格式错误"];
        return NO;
    }
    return YES;
}
- (void)STSendButtonDidClic:(UIButton*)button isFirstClic:(BOOL)isFirstClic duration:(NSInteger)duration{
    
    if (isFirstClic) {
        [self sendcodeRequest];
    }
}

- (void)STSendButtonDidCountdown:(UIButton*)button duration:(NSInteger)duration{
    [self.sendButton setTitle:[NSString stringWithFormat:@"%ld秒",duration] forState:UIControlStateNormal];
}
- (void)STSendButtonTimeEnded:(UIButton*)button{
    [self.sendButton timerEnd];
    [self.sendButton setTitle:@"获取验证码" forState:UIControlStateNormal];
}
#pragma mark --Action Method
- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)onSelectedLoginButton{
    if (self.accountTextFiled.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入用户名/手机号"];
        return;
    }
    
    if (self.pwdTextFiled.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入密码"];
        return;
    }
    [SVProgressHUD showWithStatus:@"注册中"];
    [self sendRegisterRequest];
}


#pragma mark --NetWork Method
- (void)sendcodeRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * paramDic = [NSMutableDictionary new];
    NSString * userID = [STUserManger defult].loginedUser.userID;
    if (userID.length) {
        [paramDic setObject:userID forKey:@"id"];
    }
    if (self.phoneTextFiled.text.length) {
        [paramDic setObject:self.phoneTextFiled.text forKey:@"tel"];
    }
    [paramDic setObject:@"1" forKey:@"status"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"/Rest/Login/sms_send"];
    DDLogInfo(@"url:%@",url);
    DDLogInfo(@"param:%@",paramDic);
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:paramDic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 NSDictionary * modelDic = [responseObject valueForKey:@"data"];
                                                 DDLogInfo(@"%@请求成功:resp\n%@",url,responseObject);
                                                 [self.sendButton timerBegin];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 DDLogError(@"\nurl:%@\nparam:%@\nreson:%@",url,paramDic,error.desc);
                                             }];
}
- (void)sendRegisterRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * paramDic = [NSMutableDictionary new];
    if (self.accountTextFiled.text.length) {
        [paramDic setObject:self.accountTextFiled.text forKey:@"user_nick"];
    }
    if (self.phoneTextFiled.text.length) {
        [paramDic setObject:self.phoneTextFiled.text forKey:@"user_tel"];
    }
    if (self.pwdTextFiled.text.length) {
        [paramDic setObject:self.pwdTextFiled.text forKey:@"password"];
    }
    if (self.confimTextFiled.text.length) {
        [paramDic setObject:self.confimTextFiled.text forKey:@"confirm_password"];
    }
    if (self.codeTextFiled.text.length) {
        [paramDic setObject:self.codeTextFiled.text forKey:@"sms_code"];
    }
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"/Rest/Login/register"];
    DDLogInfo(@"url:%@",url);
    DDLogInfo(@"param:%@",paramDic);

    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:paramDic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 NSDictionary * modelDic = [responseObject valueForKey:@"data"];
                                                 DDLogInfo(@"%@请求成功:resp\n%@",url,responseObject);
                                                 [SVProgressHUD showSuccessWithStatus:@"注册成功"];
                                                 TMLoginViewController * loginVc = [TMLoginViewController new];
                                                 [loginVc loginWithMobie:self.phoneTextFiled.text pwssWord:self.pwdTextFiled.text];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 DDLogError(@"\nurl:%@\nparam:%@\nreson:%@",url,paramDic,error.desc);
                                             }];
}
@end

